from fastapi import APIRouter, HTTPException
from starlette.responses import StreamingResponse

from app.common.result import Result
from app.config.logging import logger
from app.core.chat_engine import ChatEngine
from app.models.chat_payload import ChatPayload

router = APIRouter(prefix="/llm", tags=["AI大模型"])


@router.post(path="/chat", summary="会话接口", description="人机交互接口")
async def stream_chat(payload: ChatPayload):
    """
    用户与LLM交互的核心入口，流式返回
    """
    logger.info(f"ai_chat payload: {payload}")
    if payload is None or len(payload.prompt) == 0:
        return Result.fail("用户没有输入任何信息")

    try:
        chat_engine = ChatEngine(payload)

        async def event_generator():
            async for event in chat_engine.astream_events():
                # text/event-stream 固定格式
                yield event.formate_response()

        return StreamingResponse(
            content=event_generator(),
            media_type="text/event-stream",  # SSE协议
            headers={"X-Event-Source": "chat/v1"}
        )
    except Exception as e:
        logger.error(f"API错误：{e}", exc_info=True)
        raise HTTPException(status_code=500, detail="服务异常")
